package com.itheima.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.RelationException;
import com.itheima.common.R;
import com.itheima.dao.CategoryDao;
import com.itheima.dao.DishDao;
import com.itheima.dao.SetmealDao;
import com.itheima.domain.Category;
import com.itheima.domain.Dish;
import com.itheima.domain.Setmeal;
import com.itheima.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
@Transactional
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, Category> implements CategoryService {
    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private DishDao dishdao;

    @Autowired
    private SetmealDao setmealdao;

    /**
     * 分类管理分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Page getPage(Integer page, Integer pageSize) {
        Page ipage = new Page(page,pageSize);
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.orderByAsc(Category::getSort);
        ipage = categoryDao.selectMapsPage(ipage, lqw);
        return ipage;
    }

    /**
     * 菜品删除
     * @param ids
     * @return
     */
    @Override
    public R deleteWith(Long ids) {

        //查询dish表
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ids!=null,Dish::getCategoryId,ids);
        Integer dishcounts = dishdao.selectCount(lqw);
        log.info("查到的条数：{}",dishcounts);
        //查询 Setmeal表
        LambdaQueryWrapper<Setmeal> lqw2 = new LambdaQueryWrapper<>();
        lqw2.eq(ids!=null,Setmeal::getCategoryId,ids);
        Integer setmealcounts = setmealdao.selectCount(lqw2);
        log.info("查到的条数：{}",setmealcounts);

        //判断是否关联菜品
        if (dishcounts>0){
            throw new RelationException("已关联菜品");
        }
        //判断是否关联套餐
        if (setmealcounts >0){
            throw new RelationException("已关联菜品");
        }
        //执行删除
        categoryDao.deleteById(ids);
        return R.success("删除成功");
    }


}
